﻿
using EBA.Dynamic;
using EBA.IoC;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Ipc;
using System.Runtime.Remoting.Channels.Tcp;
using System.Security.Principal;
using System.Text;
using System.Threading;

namespace EBA.Framework
{
    /// <summary>
    /// 远程插件运行包装器
    /// </summary>
    [Serializable]
    public abstract class RemotingBundle: MarshalByRefObject, IDynamicContext, IDisposable
    {

        /// <summary>
        /// 初始化远程环境
        /// </summary>
        /// <param name="runtime"></param>
        /// <param name="bundleId"></param>
        public void RegisterChannels(string runtime, string bundleId)
        {
            var channelName = RemotingUris.BuildBundleChannelName(runtime, bundleId);

            SecurityIdentifier sid = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
            NTAccount account = sid.Translate(typeof(NTAccount)) as NTAccount;

            IDictionary props = new Hashtable();
            props["portName"] = channelName;
            props["name"] = channelName;
            props["exclusiveAddressUse"] = false;
            props["authorizedGroup"] = account.Value;

            BinaryServerFormatterSinkProvider serverProvider = new BinaryServerFormatterSinkProvider();
            serverProvider.TypeFilterLevel = System.Runtime.Serialization.Formatters.TypeFilterLevel.Full;

            this.Channel = new IpcChannel(props, null, serverProvider);
            ChannelServices.RegisterChannel(Channel, false);

            RemotingServices.Marshal(this, bundleId, this.GetType());

            dynamic remotingBundle = this;

            var bundleContext = new RemotingProcessBundleContext();
            bundleContext.Initialize(runtime, remotingBundle);

            this.Bundle.BundleContext = bundleContext;
        }

        IBundle Bundle { get; set; }

        /// <summary>
        /// 共享通道
        /// </summary>
        protected virtual IpcChannel Channel { get; set; }

    

        #region Dispose
        private bool _Disposed = false;
        /// <summary>
        /// 析构函数，释放资源。
        /// </summary>
        ~RemotingBundle()
        {
            Dispose(false);
        }

        /// <summary>
        /// 手动释放资源。
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
        }

        /// <summary>
        /// 手动释放资源。
        /// </summary>
        /// <param name="disposing"></param>
        protected virtual void Dispose(bool disposing)
        {
            if (!_Disposed)
            {
                if (disposing)
                {
                    this.Bundle = null;
                    this.ContextObject = null;
                    ChannelServices.UnregisterChannel(Channel);
                    this.Channel = null;
                    GC.SuppressFinalize(this);
                }
                _Disposed = true;
            }
        }


        public override object InitializeLifetimeService()
        {
            return null;
        }
        #endregion


        #region IDynamicContext
        /// <summary>
        /// 待转换的对象
        /// </summary>
        public object ContextObject
        {
            get;
            set;
        }

        /// <summary>
        /// 待转换的对象类型
        /// </summary>
        public Type ContextType
        {
            get;
            set;
        }

        /// <summary>
        /// 初始化动态转换上下文
        /// </summary>
        /// <param name="contextObject"></param>
        public void Initialize(object contextObject)
        {
            this.Bundle = (IBundle)contextObject;
            this.ContextObject = contextObject;
            this.ContextType = contextObject == null? null: contextObject.GetType();
        }
        #endregion
    }
}
